<template>

    <!-- 添加或修改对话框 -->
    <el-dialog v-model="open" :title="form.id?'修改数据':'新增数据'" width="900px" append-to-body >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="上级节点" prop="tname">
                {{form.tname}}
            </el-form-item>

            <el-form-item  v-if="form.tid===0" label="布局样式" prop="componentType" >
                <el-row :gutter="10">
                    <el-radio-group v-model="form.componentType" :disabled="form.id?true:false">
                         <el-col :span="8">
                             <el-radio :label="3" style="height: 100px;">
                                 <img src="../../../../assets/images/type01.png">
                             </el-radio>
                         </el-col>
                         <el-col :span="8">
                             <el-radio :label="2"  style="height: 100px;">
                                 <img src="../../../../assets/images/type02.png">
                             </el-radio>
                         </el-col>
                         <el-col :span="8">
                             <el-radio :label="1" style="height: 100px;" >
                                 <img src="../../../../assets/images/type03.png">
                             </el-radio>
                         </el-col>
                    </el-radio-group>
                </el-row>
            </el-form-item>

            <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>

            <el-form-item v-if="form.componentType>0" label="排序"  prop="orderNum">
                <el-input v-model.number="form.orderNum" placeholder="请输入排序值" controls-position="right" :min="0"/>
            </el-form-item>

            <el-form-item v-if="form.tid && form.tid>0" label="封面图片" prop="path">
                <el-upload
                    class="avatar-uploader"
                    :action="imageUploadUrl"
                    :headers="data.header"
                    :data="data.ossdata"
                    name="imgFile"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="form.path" :src="form.path" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
            </el-form-item>


            <el-form-item v-if="form.componentType<=2  && form.tid!=0" label="锻炼时长" prop="time">
                <el-input v-model="form.time" placeholder="锻炼时长(分钟)">
                    <template #append>(分钟)</template>
                </el-input>
            </el-form-item>
            <el-form-item v-if="form.componentType<=2  && form.tid!=0" label="能量消耗" prop="consume">
                <el-input v-model="form.consume" placeholder="能量消耗"  >
                  <template #append>(千卡)</template>
                </el-input>
            </el-form-item>

            <el-form-item v-if="form.componentType<=2 && form.tid!=0" label="锻炼所需设备" prop="equip">
                <el-input v-model="form.equip" placeholder="锻炼所需设备" />
            </el-form-item>

            <el-form-item v-if="form.componentType<=2  && form.tid!=0" label="锻炼焦点区域" prop="focus">
                <el-input v-model="form.focus" placeholder="锻炼焦点区域" />
            </el-form-item>


        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
import { reactive, ref,getCurrentInstance, ComponentInternalInstance  } from 'vue';
import { type FormRules, type FormInstance, ElMessage, type UploadFile  } from 'element-plus';
// TypeScript数据模型，约束只能传变量
import {  SubmitForm,RespModel,ExecuriseTypeResp } from '@/api/app/typescript/ExerciseType';
// 引用后台的api
import { getTypeByIdApi,addApi,updateApi,getByIdApi } from '@/api/app/exercise/type';
import { getToken } from '@/utils/auth';
// 获取当前vue3的页面this对象转换为proxy代理，查询 sys_dict_data表中的值
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

//图片上传地址
const imageUploadUrl =ref(import.meta.env.VITE_APP_BASE_API+'/oss/uploadImg');
const token=getToken();
//配置请求头的令牌
const header={
    header: {
        'Authorization': token
    }
} ;
//自己的定义额外参数
const data = reactive({
    header: {
        'Authorization': token
    },
    ossdata: {
        fatherPath:'images'
    }
});
const open = ref(false);
//得到数据表单form样式对象
const formRef = ref<FormInstance>();

//声明子组件的自定义事件 https://cn.vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
const emit = defineEmits(['refreshDataList']);

// 定义表单对象
const form = ref<SubmitForm>({
    id: undefined,
    name: '',
    componentType: 3,
    path:undefined,
    tid:0,
    tname:'顶级节点',
    orderNum:0
});


// 表单验证
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '该值不能为空', trigger: 'blur' }
    ]
});

//对话框保存按钮
const submitForm = () => {
    formRef.value.validate((valid: boolean) => {
        //验证不成功
       	if (!valid) {
       		return false;
       	}

        //修改
        if(form.value.id){
            updateApi(form.value).then(resp=>{
                ElMessage.success({
                    message: '修改成功',
                    duration: 500,
                    onClose: () => {
                        //关闭弹窗
                        open.value = false;
                        //调用重新查询数据操作
                        emit('refreshDataList');
                    }
                });

            });
        }else{
            //新增
            addApi(form.value).then(resp=>{
                ElMessage.success({
                    message: '新增成功',
                    duration: 500,
                    onClose: () => {
                        //关闭弹窗
                        open.value = false;
                        //调用重新查询数据操作
                        emit('refreshDataList');
                    }
                });

            });
        }

    });

};

//对话框取消按钮
const cancel = () => {
    open.value = false;
    resetFrom();
};


// 重置表单
const resetFrom = () => {
    // 清空表单样式
    if (formRef.value){
        formRef.value.resetFields();
    }
    // 重置值
    form.value = {
        id: undefined,
        name: '',
        componentType: 3,
        path:undefined,
        tid:0,
        tname:'顶级节点',
        userLevelId:undefined,
        orderNum:0
    };
};

//判断如果是修改操作，就要查询数据库，还原数据,要暴露出去
const init = (id?: number,pid?:number,componentType?:number) => {

    // 重置表单数据
    resetFrom();
    // id 存在则为修改
    if (id) {
        getByIdApi(id).then(resp=> {
            const data:RespModel=resp.data;

            const dataObj:SubmitForm=JSON.parse(JSON.stringify(data));

            form.value=dataObj ;
        });
    }else{
        //新增
        if(pid!=null){
            //查找上级节点的信息
            form.value.tid=pid;
            if(pid===0){
                form.value.componentType=3;
                form.value.tname='根节点';
            }else{
                //查询id的值
                getTypeByIdApi(pid).then(resp=> {
                    console.log(resp);
                    form.value.tname=resp.data.typeName;
                    //为了解决部位上传图片显示组件判断问题
                    if(componentType===0){
                        form.value.componentType=0;
                    }else{
                        form.value.componentType=resp.data.componentType;
                    }

                });
            }
        }
    }

    open.value = true;
};


// 上传图片时检查
function  beforeAvatarUpload(file) {
    console.log(file);
    //允许的图片类型
    const imgType = (file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/gif');
    //文件大小3M
    const imgLimit= (file.size / 1024 / 1024) < 3;
    if (!imgType) {
        ElMessage.error("只允许jpg、png、gif格式的图片");
        return false;
    }
    if (!imgLimit) {
        ElMessage.error("上传的图片大小不能超过3MB");
        return false;
    }

    return true;
}

/** 上传图片 */
function handleAvatarSuccess(res, file)  {
    console.log(res);
    form.value.path=res.data;
};

//https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose
defineExpose({
   	init
});

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
